package cn.lysj.framework.common.utils.job;

import cn.hutool.core.lang.Assert;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.repository.UserRepository;
import cn.lysj.framework.common.utils.message.TemplateMessageUtil;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.elm.repository.ElmOrderRepository;
import cn.lysj.framework.order.repository.FoodOrderRepository;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 16:01 2019/2/21
 * @ Description:
 **/
@Component
public class MessageTempJob {

    private static final long EXPIRES = 1000 * 60 ;  //过期时间: 1分钟

    @Resource
    private FoodOrderRepository foodOrderRepository;

    @Resource
    private ElmOrderRepository elmOrderRepository;

    @Resource
    private UserRepository userRepository;

    /*第一次10秒后执行，当执行完后1分钟后再执行*/
    @Scheduled(initialDelay = 10000, fixedDelay = 60000)
    public void queryBhpcWallet() {
        //获取当前时间前1分钟的时间搓
        long currentTime = System.currentTimeMillis();
        Assert.notNull(currentTime - EXPIRES, "time is null");
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = ftf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(currentTime - EXPIRES), ZoneId.systemDefault()));

        List<Object[]> objects = new ArrayList<>();
        Map<Object, Object> map = new HashMap<>();

        //获取平台未打印的订单
        objects = foodOrderRepository.countPlatOrderNum(time);
        for (Object[] object : objects) {
            map.put(object[0], object[1]);
        }
        //获取饿了么未打印的订单
        objects = elmOrderRepository.countElmOrderNum(time);
        for (Object[] object : objects) {
            //如果有相同的门店
            if (map.containsKey(object[0])) {
                BigInteger number = new BigInteger(String.valueOf(map.get(object[0]))).add(new BigInteger(String.valueOf(object[1])));
                map.put(object[0], number);
            } else {
                map.put(object[0], object[1]);
            }
        }
        //遍历map
        map.forEach((key, value) -> {
            User user = userRepository.findByStoreId(String.valueOf(key));
            //如果商户存在openid,则发送模板消息
            if (!ParamUtil.isBlank(user.getOfficialAccountOpenid())) {
                String templateMesage = TemplateMessageUtil.createOrderMeasureTemplateMessageJson(user.getOfficialAccountOpenid(),String.valueOf(value));
               TemplateMessageUtil.sendTemplateMessage(templateMesage);
            }

        });
    }
}
